package com.demo.youxuanmall.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                // 静态资源
                .antMatchers("/static/**", "/css/**", "/js/**", "/images/**", "/img/**").permitAll()
                // 公共页面
                .antMatchers("/", "/home", "/category/**", "/product/**", "/login", "/api/login", "/register", "/error").permitAll()
                // 其他请求
                .anyRequest().permitAll()  // 改为permitAll，依赖自定义拦截器进行权限控制
            )
            .formLogin(form -> form.disable())  // 禁用Spring Security的表单登录
            .logout(logout -> logout
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .permitAll()
            )
            .csrf(csrf -> csrf.disable())  // 禁用CSRF保护
            .headers(headers -> headers.frameOptions().disable())  // 允许iframe加载
            .sessionManagement(session -> session  // 添加Session管理配置
                .sessionFixation().migrateSession()  // 防止会话固定攻击
                .maximumSessions(1)  // 同一用户最多一个会话
                .expiredUrl("/login")  // 会话过期后跳转的页面
            );
        
        return http.build();
    }
} 